<?php declare(strict_types=1);

namespace App\Library\Core;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\ValidationData;


class Token
{
    /**
     * 发布者
     * @var
     */
    const ISSUER = 'shalabing';

    /**
     * 过期时间
     * @var
     */
    const EXP_TIME = 86400;

    /**
     * @var
     */
    const SALT_STR = 'service-gateway@2021';

    /**
     * @var
     */
    const JWT_ID = 'service-gateway';

    /**
     * 创建Token
     * @return String
     * @param $uid
     **/
    public static function createToken($userInfo)
    {
        $signer = new Sha256();
        $token = (new Builder())->setIssuer(env('ISSUER')) // self::ISSUER
            ->setId(self::JWT_ID, true) //自定义标识
            ->setIssuedAt(time()) //当前时间
            ->setExpiration(time() + self::EXP_TIME) //token有效期时长
            ->set('userInfo', json_encode($userInfo))
            ->sign($signer, self::SALT_STR)
            ->getToken();

        return (string)$token;
    }

    /**
     * 检测Token是否过期与篡改
     * @param token
     * @return array
     **/
    public static function validateToken($token = null)
    {
        $token = (new Parser())->parse((String) $token);
        $signer =  new Sha256();
        if (!$token->verify($signer, self::SALT_STR)) {
            return false; //签名不正确
        }

        $validationData = new ValidationData();
        $validationData->setIssuer(env('ISSUER'));
        $validationData->setId(self::JWT_ID);//自字义标识

        return $token->validate($validationData) ? json_decode($token->getClaim('userInfo') , true) : [];
    }
}